package com.mason.forum.utils;

import com.mason.forum.config.APPConfig;
import com.mason.forum.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-09-02
 * Time: 22:39
 */

public class SessionUtils {
    /**
     * 得到当前登录用户
     * @param request 请求
     * @return 当前登录用户信息
     */
    public static User getUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session == null ? null : (User) session.getAttribute(APPConfig.USER_SESSION_KEY);
    }

    /**
     * 保存用户信息
     * @param request 请求
     */
    public static void setUser(HttpServletRequest request, User userInfo) {
        HttpSession session = request.getSession(true);
        session.setAttribute(APPConfig.USER_SESSION_KEY, userInfo);
        session.setMaxInactiveInterval(-1);//session永不过期
    }

    /**
     * 注销
     * @param request 请求
     */
    public static void remove(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(APPConfig.USER_SESSION_KEY) != null) {
            session.removeAttribute(APPConfig.USER_SESSION_KEY);
//            session.invalidate();消耗 session
        }
    }
}
